package org.class2table.sync;

import cn.hutool.core.collection.CollectionUtil;
import org.class2table.core.Class2TableException;
import org.class2table.sync.bean.CompareResult;
import org.class2table.sync.bean.ExeSqlInfo;
import org.class2table.sync.bean.TableResult;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class SyncExecutor {

    private static Map<String, Connection> tenantConnectionMap;

    public static void init(Map<String, Connection> tenantConnectionMap) {
        if (CollectionUtil.isEmpty(tenantConnectionMap)) {
            throw new Class2TableException("SyncExecutor init failed! tenantConnectionMap is empty!");
        }
        SyncExecutor.tenantConnectionMap = tenantConnectionMap;
    }

    public static void exeSync(List<CompareResult> compareResults) {
        for (CompareResult compareResult : compareResults) {
            String dbName = compareResult.getDbName();
            Connection connection = tenantConnectionMap.get(dbName);
            if (Objects.isNull(connection)) {
                throw new Class2TableException(String.format("Sync failed! connection for [%s] is null!", dbName));
            }
            Statement statement;
            try {
                statement = connection.createStatement();
            } catch (Exception e) {
                throw new Class2TableException(String.format("Sync failed! createStatement of [%s] failed!", dbName),e);
            }
            List<TableResult> tableResults = compareResult.getTableResults();
            for (TableResult tableResult : tableResults) {
                List<ExeSqlInfo> exeSqlInfos = tableResult.getExeSqlInfos();
                for (ExeSqlInfo exeSqlInfo : exeSqlInfos) {
                    List<String> sqls = exeSqlInfo.getSqls();
                    for (String sql : sqls) {
                        try {
                            statement.execute(sql);
                        } catch (Exception e) {
                            throw new Class2TableException(String.format("SyncExecutor run sql failed! wrong sql is [%s]!", sql), e);
                        }
                    }
                }
            }
        }
    }

}